package com.gxuwz.endrskyweather.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.gxuwz.endrskyweather.R;
import com.gxuwz.endrskyweather.model.ForecastDay;

import java.util.ArrayList;
import java.util.List;

public class ForecastAdapter extends RecyclerView.Adapter<ForecastAdapter.ForecastViewHolder> {

    private List<ForecastDay> forecastDays = new ArrayList<>();

    public void updateData(List<ForecastDay> newForecastDays) {
        this.forecastDays = newForecastDays != null ? newForecastDays : new ArrayList<>();
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ForecastViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_15d_forecast, parent, false);
        return new ForecastViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ForecastViewHolder holder, int position) {
        ForecastDay day = forecastDays.get(position);
        holder.bind(day);
    }

    @Override
    public int getItemCount() {
        return forecastDays.size();
    }

    static class ForecastViewHolder extends RecyclerView.ViewHolder {
        private final TextView dateView;
        private final ImageView weatherIcon;
        private final TextView weatherView;
        private final TextView tempMaxView;
        private final TextView tempMinView;
        private final TextView windView;
        private final TextView windLevelView;

        ForecastViewHolder(View itemView) {
            super(itemView);
            dateView = itemView.findViewById(R.id.tv_date_15d_forecast);
            weatherView = itemView.findViewById(R.id.tv_weather_15d_forecast);
            weatherIcon = itemView.findViewById(R.id.iv_weather_icon_15d_forecast);
            tempMaxView = itemView.findViewById(R.id.tv_temp_max_15d_forecast);
            tempMinView = itemView.findViewById(R.id.tv_temp_min_15d_forecast);
            windView = itemView.findViewById(R.id.tv_wind_15d_forecast);
            windLevelView = itemView.findViewById(R.id.tv_wind_level_15d_forecast);
        }

        void bind(ForecastDay day) {
            dateView.setText(day.getTime());
            weatherView.setText(day.getWeather());
            weatherIcon.setImageResource(itemView.getContext().getResources().getIdentifier(day.getDayWeatherPic(), "drawable", itemView.getContext().getPackageName()));
            tempMaxView.setText(day.getTemperatureMax());
            tempMinView.setText(day.getTemperatureMin());
            windView.setText(day.getWind());
            windLevelView.setText(day.getWindPow());
            // TODO: Set appropriate weather icon based on day.getWeatherCode()
        }
    }
}
